package com.nhjf.admin.controller;

import com.nhjf.admin.common.filter.StringEditor;
import org.jsoup.Jsoup;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.nhjf.admin.common.util.LogMessage;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lixx
 * 
 */
public class BaseController {

	/**
	 * 自动将yyyy-MM-dd格式的参数转换成Date型参数
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
		binder.registerCustomEditor(String.class, new StringEditor());
	}
	
	public  void logwrite(Class clazz, String log) {
		LogMessage.logwrite(clazz, log);
	}
    // 请求路径
	public String getWebSite(HttpServletRequest request) {
		StringBuffer sb = new StringBuffer();
		sb.append(request.getScheme());
		sb.append("://");
		sb.append(request.getServerName());
		if (!"80".equals(String.valueOf(request.getServerPort()))) {
			sb.append(":");
			sb.append(request.getServerPort());

		}
		if (!"/".equals(request.getContextPath().trim())
				&& request.getContextPath() != null
				&& !"".equals(request.getContextPath().trim())) {
			sb.append(request.getContextPath());
		}

		return sb.toString();
	}
	/**
	 * ajax请求时，异步返回请求信息
	 * 
	 * @param res
	 *            当前要返回的response对象
	 * @param str
	 *            要返回的json字符串
	 */
	public void ajaxWrite(HttpServletResponse res, String str) {
		try {
			res.setContentType("text/json;charset=UTF-8");
			res.setHeader("Cache-Control","no-cache");
			res.setCharacterEncoding("utf-8");
			PrintWriter out = res.getWriter();
			out.write(str);
			out.close();
		} catch (Exception e) {
			this.logwrite(this.getClass(), e.getMessage());
		}
	}

	public void ajaxWrite(HttpServletResponse res, String str, String contentType) {
		try {
			res.setContentType(contentType);
			res.setHeader("Cache-Control","no-cache");
			res.setCharacterEncoding("utf-8");
			PrintWriter out = res.getWriter();
			out.write(str);
			out.close();
		} catch (Exception e) {
			this.logwrite(this.getClass(), e.getMessage());
		}
	}
	
}
